// 高阶版
const throttle = (func,wait = 0,execFirstCall) => {
    let timeout = null;
    let args;
    let firstCallTimstamp

    function throttled(...arg) {
        if(!firstCallTimstamp)firstCallTimstamp = new Date().getTime()
        if(!execFirstCall || !args){
            console.log("set args",arg);
            args = arg
        }
        if(timeout){
            clearTimeout(timeout)
            timeout = null
        }
        // 以promise 返回
        return new Promise((res,rej)=>{
            if(new Date().getTime() - firstCallTimstamp >= wait){
                try {
                    const result = await func.apply(this,args)
                    res(result)
                } catch (e) {
                    rej(e)
                }finally {
                    cancel()
                }
            }
        },firstCallTimstamp+wait-new Date().getTime())
    }

    function cancel(){
        clearTimeout(timeout)
        args = null
        timeout = null
        firstCallTimestamp = null
    }
    function flush() {
        cancel()
        return func.apply(this,args)
    }

    throttled.cancel = cancel
    throttled.flush = flush
    return throttled
}